package com.sicnu.comments.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sicnu.comments.entity.CommentsDO;
import com.sicnu.comments.entity.CommentVO;
import com.sicnu.comments.mapper.CommentMapper;
import com.sicnu.comments.service.CommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentsDO> implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public List<CommentVO> getTopLevelComments(Integer resourceId) {
        List<CommentsDO> commentDOs = commentMapper.selectTopLevelComments(resourceId);
        return convertToVOList(commentDOs);
    }

    @Override
    public List<CommentVO> getRepliesByTopLevelCommentId(Integer topLevelCommentId) {
        List<CommentsDO> commentDOs = commentMapper.selectRepliesByTopLevelCommentId(topLevelCommentId);
        return convertToVOList(commentDOs);
    }

    @Override
    public List<CommentVO> getRepliesByParentCommentId(Integer parentCommentId) {
        List<CommentsDO> commentDOs = commentMapper.selectRepliesByParentCommentId(parentCommentId);
        return convertToVOList(commentDOs);
    }

    @Override
    public List<CommentVO> getCommentTree(Integer resourceId) {
        List<CommentVO> topLevelComments = getTopLevelComments(resourceId);
        topLevelComments.forEach(comment -> {
            List<CommentVO> replies = getRepliesByTopLevelCommentId(comment.getCommentId());
            comment.setReplies(replies);
        });
        return topLevelComments;
    }

    @Override
    public CommentsDO addComment(CommentsDO comment) {
        comment.setCreatedAt(new Date());
        comment.setUpdatedAt(new Date());

        if (comment.getParentCommentId() != null) {
            CommentsDO parentComment = getById(comment.getParentCommentId());
            if (parentComment != null) {
                comment.setTopLevelCommentId(parentComment.getTopLevelCommentId() != null ?
                        parentComment.getTopLevelCommentId() : parentComment.getCommentId());
            }
        }

        save(comment);
        return comment;
    }

    private CommentVO convertToVO(CommentsDO commentDO) {
        CommentVO commentVO = new CommentVO();
        BeanUtils.copyProperties(commentDO, commentVO);
        return commentVO;
    }

    private List<CommentVO> convertToVOList(List<CommentsDO> commentDOs) {
        return commentDOs.stream().map(this::convertToVO).collect(Collectors.toList());
    }
}